package com.zrfintech.manage.service;


import com.zrfintech.domain.MgRole;
import com.zrfintech.domain.MgRoleMenuPermission;
import com.zrfintech.domain.MgRolePageOptionPermission;
import com.zrfintech.service.MgRoleMenuPermissionRepo;
import com.zrfintech.service.MgRolePageOptionPermissionRepo;
import com.zrfintech.service.MgRoleRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class MgRoleService {

    @Autowired
    private MgRoleRepo mgRoleRepo;

    @Autowired
    private MgRoleMenuPermissionRepo mgRoleMenuPermissionRepo;

    @Autowired
    private MgRolePageOptionPermissionRepo mgRolePageOptionPermissionRepo;

    @Transactional(rollbackFor = Exception.class)
    public int upsert(MgRole mgRole, List<String> menuCodeList, List<String> optionCodeList, List<Long> dataIdList) {
        Long id = mgRole.getId();
        if (id == null || id == 0L) {
            mgRoleRepo.create(mgRole);
        } else {
            MgRole targetMgRole = mgRoleRepo.getById(id);
            if (targetMgRole != null) {
                targetMgRole.setRoleName(mgRole.getRoleName());
                mgRoleRepo.updateById(targetMgRole);
            }
        }
        for (String menuCode : menuCodeList) {
            MgRoleMenuPermission mgRoleMenuPermission = new MgRoleMenuPermission();
            mgRoleMenuPermission.setRoleCode(mgRole.getRoleCode());
            mgRoleMenuPermission.setMenuCode(menuCode);
            mgRoleMenuPermissionRepo.create(mgRoleMenuPermission);
        }
        for (String optionCode : optionCodeList) {
            MgRolePageOptionPermission mgRolePageOptionPermission = new MgRolePageOptionPermission();
            mgRolePageOptionPermission.setRoleCode(mgRole.getRoleCode());
            mgRolePageOptionPermission.setPageOptionCode(optionCode);
            mgRolePageOptionPermissionRepo.create(mgRolePageOptionPermission);
        }
        return 1;
    }
}
